<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <!--顶部搜索 -->
      <div class="top-operate-default">
        <div class="search-item">
          <label>订单搜索：</label>
          <el-select v-model="order.textCol">
            <el-option label="主订单号" value="projectOrderNo"></el-option>
            <el-option label="子订单号" value="orderNo"></el-option>
          </el-select>
          <el-input style="width: 200px" v-model="order.textValue" placeholder="请输入内容"></el-input>         
          <label class="mar-l-20">供应商：</label>
          <el-select v-model="order.supplierId" placeholder="请选择供应商" clearable>
            <el-option v-for="supplier in supplierList" :key="supplier.supplierId" :label="supplier.supplierName" :value="supplier.supplierId">
            </el-option>
          </el-select>
          <label class="mar-l-20">发货时间：</label>
          <el-date-picker
            v-model="order.deliveryTimeArray"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            start-placeholder="发货日期"
            end-placeholder="发货日期"
            :picker-options="deliveryTimeOptions">
          </el-date-picker>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button plain="" @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!-- 全选、操作 -->
      <div>
        <div class="pad-t-15 pad-b-15 font-14 v-align-c">
          <el-button @click="exportAll">导出</el-button>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="dataList" v-loading="listLoading" element-loading-text="加载中">
          <el-table-column min-width="240px" label="供应商名称" prop="supplierName" fixed="left"></el-table-column>
          <el-table-column width="240px" label="供应商子订单号" prop="orderNo"></el-table-column>
          <el-table-column width="240px" label="关联订单号" prop="projectOrderNo"></el-table-column>
          <el-table-column width="200px" label="发货时间" prop="deliveryTime"></el-table-column>
          <el-table-column width="200px" label="完成时间" prop="completeTime"></el-table-column>
          <el-table-column width="200px" label="商品金额（元）" prop="supplyGoodsPrice">
            <template slot-scope="scope">
              <div>￥{{scope.row.supplyGoodsPrice||''}}</div>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="合计金额（元）">
            <template slot-scope="scope">
              <div>￥{{ ((scope.row.supplyGoodsPrice||0) * 1 + (scope.row.freight||0) * 1).toFixed(2) }}</div>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="结算类型">
            <template slot-scope="scope">
              <div>{{ dict.settlementType[scope.row.settlementType] }}</div>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="商品结算金额（元）">
            <template slot-scope="scope">
              <!-- 扣率代销：=商品金额×（1-扣率） -->
              <div v-if="scope.row.settlementType == 20">￥{{ ((scope.row.supplyGoodsPrice*1||0)* (1-(scope.row.settlementRate*1/100||0))).toFixed(2) }}</div>
              <div v-else>￥{{ scope.row.supplyGoodsPrice }}</div>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="结算运费（元）" prop="freight">
            <template slot-scope="scope">
              <div v-if="scope.row.freight">￥{{scope.row.freight}}</div>
            </template>
          </el-table-column>
          <el-table-column width="100px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="doLinkDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]" 
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import { getDictByGroupName } from '@/api/common/common'
  import { pagingSupplierAccount } from '@/api/finace/supplierAccount'
  import { listSupplier } from '@/api/user/supplier'
  import { downloadFile } from '@/api/common/common'

  export default {
    data() {
      return {
        total: 0,
        listLoading: false,
        searchListQuery: {},
        defaultQuery: {
          enterpriseId: this.getEnterpriseId(),
          supplierId: '',
          currentPage: 1,
          size: 10
        },
        order: {
          deliveryTimeArray: [],
          textCol: 'projectOrderNo',
          textValue: '',
          supplierId: ''
        },
        deliveryTimeOptions: {
          shortcuts: [{
            text: '昨日',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              start.setDate(start.getDate() - 1)
              end.setDate(end.getDate() - 1)
              start.setHours(0)
              start.setMinutes(0)
              start.setSeconds(0)
              end.setHours(23)
              end.setMinutes(59)
              end.setSeconds(59)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '今日',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              start.setHours(0)
              start.setMinutes(0)
              start.setSeconds(0)
              end.setHours(23)
              end.setMinutes(59)
              end.setSeconds(59)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '上周',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              // 今天本周的第几天
              let nowDayOfWeek = start.getDay()
              if (nowDayOfWeek === 0) {
                // 周日
                nowDayOfWeek = 6
              } else {
                nowDayOfWeek = nowDayOfWeek - 1
              }
              start.setDate(start.getDate() - nowDayOfWeek - 7)
              end.setDate(start.getDate() + 6)
              start.setHours(0)
              start.setMinutes(0)
              start.setSeconds(0)
              end.setHours(23)
              end.setMinutes(59)
              end.setSeconds(59)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '本周',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              // 今天本周的第几天
              let nowDayOfWeek = start.getDay()
              if (nowDayOfWeek === 0) {
                // 周日
                nowDayOfWeek = 6
              } else {
                nowDayOfWeek = nowDayOfWeek - 1
              }
              start.setDate(start.getDate() - nowDayOfWeek)
              end.setDate(start.getDate() + 6)
              start.setHours(0)
              start.setMinutes(0)
              start.setSeconds(0)
              end.setHours(23)
              end.setMinutes(59)
              end.setSeconds(59)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '上月',
            onClick(picker) {
              const start = new Date()
              start.setMonth(start.getMonth() - 1)
              start.setDate(1)
              const nextMonth = start.getMonth() + 1
              const nextMonthFirstDay = new Date(start.getFullYear(), nextMonth, 1)
              const oneDay = 1000 * 60 * 60 * 24
              const end = new Date(nextMonthFirstDay.getTime() - oneDay)
              start.setHours(0)
              start.setMinutes(0)
              start.setSeconds(0)
              end.setHours(23)
              end.setMinutes(59)
              end.setSeconds(59)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '本月',
            onClick(picker) {
              const start = new Date()
              start.setDate(1)
              const nextMonth = start.getMonth() + 1
              const nextMonthFirstDay = new Date(start.getFullYear(), nextMonth, 1)
              const oneDay = 1000 * 60 * 60 * 24
              const end = new Date(nextMonthFirstDay.getTime() - oneDay)
              start.setHours(0)
              start.setMinutes(0)
              start.setSeconds(0)
              end.setHours(23)
              end.setMinutes(59)
              end.setSeconds(59)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        dict: {
          settlementType: {}
        },
        dataList: [],
        supplierList: []
      }
    },
    // 初始化页面
    created() {
      this.searchListQuery = { ...this.defaultQuery }
      // 获取数据字典
      getDictByGroupName('VillageSupplierDTO').then(response => {
        Object.assign(this.dict, response.data)
      })
      // 获取供应商
      listSupplier({ enterpriseId: this.getEnterpriseId() }).then(response => {
        if (response.isError) return
        this.supplierList = response.data
      })
      this.initList()
    },
    mounted() {
    },
    methods: {
      initList() {
        this.listLoading = true
        this.setSearchListQuery()
        pagingSupplierAccount(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
        })
      },
      // 查询条件
      setSearchListQuery() {
        const currentPage = this.searchListQuery.currentPage
        const size = this.searchListQuery.size
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.supplierId = this.order.supplierId
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.size = size
        this.searchListQuery.startTime = (this.order.deliveryTimeArray && this.order.deliveryTimeArray.length > 0) ? this.order.deliveryTimeArray[0] : ''
        this.searchListQuery.endTime = (this.order.deliveryTimeArray && this.order.deliveryTimeArray.length > 1) ? this.order.deliveryTimeArray[1] : ''
        this.searchListQuery[this.order.textCol] = this.order.textValue
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        this.searchListQuery = { ... this.defaultQuery }
        this.order = {
          deliveryTimeArray: [],
          textCol: 'projectOrderNo',
          textValue: '',
          supplierId: ''
        }
        this.initList()
      },
      // 查看详情事件
      doLinkDetail(row) {
        const routeData = this.$router.resolve({
          path: '/order/apart-detail',
          query: { apartOrderId: row.apartOrderId }
        })
        window.open(routeData.href, '_blank')
      },
      exportAll() {
        this.setSearchListQuery()
        downloadFile('/finace/supplierAccount/exportOrder', this.searchListQuery, '供应商对账报表.xlsx')
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>

</style>